//
//  WKSettingViewController.m
//  Walk
//
//  Created by cesh on 16/9/2.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKSettingViewController.h"
#import "WKEditViewController.h"
#import "WKLoginViewController.h"
#import <IQKeyboardManager.h>
#import <SVProgressHUD.h>
#import <EMSDK.h>
#import "JLDoubleSlider.h"
#import "SEFilterControl.h"

@interface WKSettingViewController ()
{
    JLDoubleSlider *_slider;
}
@property (weak, nonatomic) IBOutlet UIImageView *backImg;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UIView *radarView;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *genderAndAge;
@property (weak, nonatomic) IBOutlet UIView *feedbackView;
@property (weak, nonatomic) IBOutlet UIView *clearCacheView;
@property (weak, nonatomic) IBOutlet UILabel *cacheLbl;

@property (strong, nonatomic) UITextView *feedbackTextView;

@property(nonatomic,strong) SEFilterControl *genderSlider;
@property (weak, nonatomic) IBOutlet UIImageView *aboutUs;

@end

@implementation WKSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.aboutUs.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openAboutUs)];
    [self.aboutUs addGestureRecognizer:tap];
    
    [IQKeyboardManager sharedManager].enable = YES;
    
    self.backImg.userInteractionEnabled = YES;
    [self.backImg addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismiss)]];
    
    NSMutableArray *imgs = [NSMutableArray arrayWithContentsOfFile:userImagesPath];
    UIImage *icon = [UIImage imageWithData:imgs[0]];
    self.iconView.image = icon;
    
    self.iconView.layer.cornerRadius = 35;
    self.iconView.layer.masksToBounds = YES;
    
    UITapGestureRecognizer *tapOnFeedback = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(feedback)];
    [self.feedbackView addGestureRecognizer:tapOnFeedback];
    
    UITapGestureRecognizer *tapOnClearCache = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clearCache)];;
    [self.clearCacheView addGestureRecognizer:tapOnClearCache];
    
    [self setupDoubleSlider];
    [self setupGenderSlider];
    
    //获取缓存空间的大小
    NSInteger size = [[SDImageCache sharedImageCache]getSize];
    float sizeM = size * 1.0 / 1024 / 1024;
    self.cacheLbl.text = [NSString stringWithFormat:@"%.1lfM", sizeM];

    [self.radarView addSubview:_slider];
    
}

- (void)openAboutUs {
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://junvalley.com/walk/Web/aboutUs"]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //获取持久化的数据
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:userInfoPath];
    NSLog(@"设置界面 userInfo%@", dict);
    self.nameLabel.text = dict[@"nickname"];
    NSString *gender = [dict[@"sex"] isEqual:@"1"] ? @"男" : @"女";
    NSString *birthday = dict[@"birthday"];
    NSString *year = [birthday substringToIndex:4];
    NSString *age = [NSString stringWithFormat:@"%i", 2016 - [year intValue]];
    self.genderAndAge.text = [NSString stringWithFormat:@"%@/%@", gender, age];
}

- (void)clearCache {
    [SVProgressHUD showWithStatus:@"删除中..."];
    [[SDImageCache sharedImageCache]clearDiskOnCompletion:^{
        [SVProgressHUD dismiss];
    }];
    
    NSInteger size = [[SDImageCache sharedImageCache]getSize];
    float sizeM = size * 1.0 / 1024 / 1024;
    self.cacheLbl.text = [NSString stringWithFormat:@"%.1lfM", sizeM];
}

- (void)feedback {
    //弹出反馈的view
    WKPopView *popV = [WKPopView showWithType:PopViewTypeFeedback];
    UITextView *textView = [[UITextView alloc]init];
    textView.size = CGSizeMake(popV.centerView.width - 20, popV.centerView.height * 0.6);
    textView.center = CGPointMake(popV.centerView.width * 0.5, popV.centerView.height * 0.6);
    textView.backgroundColor = [UIColor colorWithRed:0xf0 / 255.0 green:0xf0 / 255.0 blue:0xf0 / 255.0 alpha:1.0];
    [textView becomeFirstResponder];
    popV.centerView.top -= screenH * 0.2;
    [popV.centerView addSubview:textView];
    self.feedbackTextView = textView;
    
    UIView *topView = [[UIView alloc]init];
    topView.size = CGSizeMake(screenW, 54);
    topView.origin = CGPointZero;
    topView.backgroundColor = [UIColor colorWithRed:0x4a / 255.0 green:0x4a / 255.0 blue:0x4a / 255.0 alpha:1.0];
    
    UILabel *title = [[UILabel alloc]init];
    title.text = @"意见反馈";
    title.font = [UIFont systemFontOfSize:16.0];
    title.textColor = [UIColor whiteColor];
    [title sizeToFit];
    title.center = CGPointMake(screenW * 0.5, 22 + title.height * 0.5);
    [topView addSubview:title];
    
    UIButton *cancel = [[UIButton alloc]init];
    cancel.size = CGSizeMake(50, 30);
    cancel.origin = CGPointMake(10, 18);
    [cancel setBackgroundImage:[UIImage imageNamed:@"btn_normal"] forState:UIControlStateNormal];
    [cancel setBackgroundImage:[UIImage imageNamed:@"btn_highlight"] forState:UIControlStateHighlighted];
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel addTarget:self action:@selector(cancelFeedBack) forControlEvents:UIControlEventTouchUpInside];
    [cancel.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [topView addSubview:cancel];
    
    UIButton *send = [[UIButton alloc]init];
    send.size = CGSizeMake(50, 30);
    send.origin = CGPointMake(screenW - 10 - send.width, 18);
    [send setBackgroundImage:[UIImage imageNamed:@"btn_normal"] forState:UIControlStateNormal];
    [send setBackgroundImage:[UIImage imageNamed:@"btn_highlight"] forState:UIControlStateHighlighted];
    [send setTitle:@"发送" forState:UIControlStateNormal];
    [send.titleLabel setFont:[UIFont systemFontOfSize:14.0]];
    [send addTarget:self action:@selector(sendFeedBack) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:send];
    
    [popV addSubview:topView];
}
- (void)cancelFeedBack {
    [WKPopView dismiss];
}
- (void)sendFeedBack {
    [WKPopView dismiss];
    //发送反馈信息
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    NSDictionary *dict = @{
                           @"token" : [NSDictionary dictionaryWithContentsOfFile:userInfoPath][@"token"],
                           @"content" : self.feedbackTextView.text
                           };
    
    [mgr POST:[NSString stringWithFormat:@"%@Notice/feedback", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"反馈成功 %@", responseObject);
        [WKPopView showWithType:PopViewTypeFeedbackSuccess];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [WKPopView dismiss];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"反馈失败 %@", error);
    }];
}


- (IBAction)editProfile:(id)sender {
    WKEditViewController *editVC = [[WKEditViewController alloc]init];
    [self presentViewController:editVC animated:YES completion:nil];
}
- (void)setupDoubleSlider {
    _slider = [[JLDoubleSlider alloc]initWithFrame:CGRectMake(screenW - 200 - 20, - 20, 200, 20)];
    _slider.minNum = 18;
    _slider.maxNum = 50;
    _slider.currentMinValue = 25;
    _slider.currentMaxValue = 35;
    _slider.minTintColor = [UIColor colorWithRed:0xd8 / 255.0 green:0xd8 / 255.0 blue:0xd8 / 255.0 alpha:1.0];
    _slider.maxTintColor = [UIColor colorWithRed:0xd8 / 255.0 green:0xd8 / 255.0 blue:0xd8 / 255.0 alpha:1.0];
    _slider.mainTintColor = [UIColor colorWithRed:0x27 / 255.0 green:0x88 / 255.0 blue:0xff / 255.0 alpha:1.0];
    
}

- (void)setupGenderSlider {
    _genderSlider = [[SEFilterControl alloc]initWithFrame:CGRectMake(screenW - 230, 75, 220, 15) Titles:[NSArray arrayWithObjects:@"男", @"不限", @"女",nil]];
//    [_genderSlider addTarget:self action:@selector(filterValueChanged:) forControlEvents:UIControlEventTouchUpInside];
    [_genderSlider setProgressColor:[UIColor colorWithRed:0xd8 / 255.0 green:0xd8 / 255.0 blue:0xd8 / 255.0 alpha:1.0]];//设置滑杆的颜色
    [_genderSlider setTopTitlesColor:[UIColor colorWithRed:0x27 / 255.0 green:0x88 / 255.0 blue:0xff / 255.0 alpha:1.0]];//设置滑块上方字体颜色

    int index = (int)[[NSUserDefaults standardUserDefaults]integerForKey:@"selectedGender"];
    [_genderSlider setSelectedIndex:index];


    [_genderSlider setTitlesFont:[UIFont systemFontOfSize:12.0]];
    [self.radarView addSubview:_genderSlider];
}

- (void)dismiss {
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //退出控制器的时候保存当前设置并将设置发送至服务器
    NSLog(@"%@ %@",_slider.minLabel.text, _slider.maxLabel.text);
    NSLog(@"选中的gender %d", _genderSlider.SelectedIndex);//0 不限 1 男 2 女
    NSInteger index = _genderSlider.SelectedIndex;
    [[NSUserDefaults standardUserDefaults]setInteger:index  forKey:@"selectedGender"];
    
    NSString *sex_set = _genderSlider.SelectedIndex == 0 ? @"1" : _genderSlider.SelectedIndex == 1 ? @"0" : @"2";
    
    
    
    NSDictionary *userinfo = [NSDictionary dictionaryWithContentsOfFile:userInfoPath];
    NSDictionary *dict = @{
                           @"token" : userinfo[@"token"],
                           @"age_set_min" : _slider.minLabel.text,
                           @"age_set_max" : _slider.maxLabel.text,
                           @"sex_set" : sex_set
                           };
    NSLog(@"%@", dict);
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@User/saveSetting", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"雷达设置 %@", responseObject);
        //将最小年龄和最大年龄保存至本地
        [[NSUserDefaults standardUserDefaults]setValue:@[_slider.minLabel.text, _slider.maxLabel.text] forKey:@"userPreferAge"];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//删除账号
- (IBAction)deleteAccount:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确定要删除账号吗？" message:@"账号信息将永久删除" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
        
        NSDictionary *userinfo = [NSDictionary dictionaryWithContentsOfFile:userInfoPath];
        NSDictionary *dict = @{
                               @"token" : userinfo[@"token"]
                               };
        [mgr POST:[NSString stringWithFormat:@"%@User/deleteAccount", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"删除帐号 %@", responseObject);
            [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"didLogin"];
            //弹出登录界面
            WKLoginViewController *loginVC = [[WKLoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:^{
                
                //退出环信的登录
                EMError *error = [[EMClient sharedClient] logout:YES];
                if (!error) {
                    NSLog(@"环信退出成功");
                }
                
                
                NSFileManager *fileManager = [NSFileManager defaultManager];
                BOOL userinfoHave=[[NSFileManager defaultManager] fileExistsAtPath:userInfoPath];
                if (!userinfoHave) {
                    NSLog(@"userInfoPath no  have");
                    return ;
                }else {
                    NSLog(@"userInfoPath have");
                    BOOL userinfoDele= [fileManager removeItemAtPath:userInfoPath error:nil];
                    if (userinfoDele) {
                        NSLog(@"userInfoPath dele success");
                    }else {
                        NSLog(@"userInfoPath dele fail");
                    }
                    
                }
                BOOL userimgHave=[[NSFileManager defaultManager] fileExistsAtPath:userImagesPath];
                if (!userimgHave) {
                    NSLog(@"userimg no  have");
                    return ;
                }else {
                    NSLog(@"userimg have");
                    BOOL userimgDele= [fileManager removeItemAtPath:userImagesPath error:nil];
                    if (userimgDele) {
                        NSLog(@"userimg Dele success");
                    }else {
                        NSLog(@"userimg Dele fail");
                    }
                }
                
            }];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:confirm];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}


//退出帐号
- (IBAction)logOut:(id)sender {
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                     @"text/html",
                                                     @"image/jpeg",
                                                     @"image/png",
                                                     @"application/octet-stream",
                                                     @"text/json",
                                                     nil];
    
    [mgr POST:[NSString stringWithFormat:@"%@User/logout", URL] parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"退出帐号 %@", responseObject);
        [[NSUserDefaults standardUserDefaults]setBool:NO forKey:@"didLogin"];
        //弹出登录界面
        WKLoginViewController *loginVC = [[WKLoginViewController alloc]init];
        [self presentViewController:loginVC animated:YES completion:^{
            
            //退出环信的登录
            EMError *error = [[EMClient sharedClient] logout:YES];
            if (!error) {
                NSLog(@"环信退出成功");
            }
            
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            BOOL userinfoHave=[[NSFileManager defaultManager] fileExistsAtPath:userInfoPath];
            if (!userinfoHave) {
                NSLog(@"userInfoPath no  have");
                return ;
            }else {
                NSLog(@"userInfoPath have");
                BOOL userinfoDele= [fileManager removeItemAtPath:userInfoPath error:nil];
                if (userinfoDele) {
                    NSLog(@"userInfoPath dele success");
                }else {
                    NSLog(@"userInfoPath dele fail");
                }
                
            }
            BOOL userimgHave=[[NSFileManager defaultManager] fileExistsAtPath:userImagesPath];
            if (!userimgHave) {
                NSLog(@"userimg no  have");
                return ;
            }else {
                NSLog(@"userimg have");
                BOOL userimgDele= [fileManager removeItemAtPath:userImagesPath error:nil];
                if (userimgDele) {
                    NSLog(@"userimg Dele success");
                }else {
                    NSLog(@"userimg Dele fail");
                }
            }
            
        }];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
    
}

@end
